package com.wx.rabbitmq.task;

import com.alibaba.fastjson.JSON;
import com.wx.rabbitmq.dao.BrokerMessageLogDao;
import com.wx.rabbitmq.entity.BrokerMessageLog;
import com.wx.rabbitmq.entity.Order;
import com.wx.rabbitmq.producer.RabbitOrderSender;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.Date;
import java.util.List;

import static com.wx.rabbitmq.constant.MessageStatus.MESSAGE_STATUS_3;

/**
 * @author wx
 * @Description:
 * @date 2018/12/3 000317:12
 */
@Component
public class RetryMessageTasker {

    @Autowired
    private RabbitOrderSender rabbitOrderSender;

    @Autowired
    private BrokerMessageLogDao brokerMessageLogDao;

    /**
     * @description: 定时任务补偿未被消费成功的消息  启动项目3秒后每隔30秒扫描一次
     * @author: wx
     * @date: 2018/12/3 0003
     * @param
     * @return: void
     */
    @Scheduled(initialDelay = 3000, fixedDelay = 30000)
    public void reSend(){
        System.err.println("---------------定时任务开始---------------");
        //pull status = 0 and timeout message
        List<BrokerMessageLog> list = brokerMessageLogDao.queryStatusAndTimeoutMessage();
        if (CollectionUtils.isEmpty(list)){
            return;
        }
        list.forEach(messageLog -> {
            if(messageLog.getTryCount() >= 3){
                //尝试次数>=3次 消息状态更新为投递失败，需要人工人工补偿
                brokerMessageLogDao.changeBrokerMessageLogStatus(messageLog.getMessageId(), MESSAGE_STATUS_3, new Date());
            } else {
                // 更新消息发送次数
                brokerMessageLogDao.updateReSend(messageLog.getMessageId(),  new Date());
                Order reSendOrder =  JSON.parseObject(messageLog.getMessage(), Order.class);
                try {
                    //再次发送消息
                    rabbitOrderSender.sendOrder(reSendOrder);
                } catch (Exception e) {
                    e.printStackTrace();
                    System.err.println("-----------异常处理-----------");
                }
            }
        });

    }

}
